<?php

namespace App\Home\Controllers;

use App\Admin\Filters\SystemMediaFilter;
use App\Admin\Requests\SystemMediaCategoryRequest;
use App\Admin\Requests\SystemMediaRequest;
use App\Admin\Resources\SystemMediaResource;
use App\Admin\Models\SystemMedia;
use App\Admin\Models\SystemMediaCategory;
use App\Admin\Models\Config;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SystemMediaCategoryController extends Controller
{
    /**
	* showdoc
	* @catalog 接口简介/全局相关
	* @title 文件上传
	* @description 文件上传的接口
	* @method POST
	* @url /home-api/system-media-categories/{category_id}/system-media
    * @param category_id 是 int 分类ID，地址栏参数，固定传1
    * @param file 是 上传文件
	* @return {"origin_filename":"958fac2089caf53ede5497e4412554cd.jpeg","filename":"9ec2a7c169979cb8d7c78d16c505adcf.jpeg","ext":"jpeg","path":"\/uploads\/9ec2a7c169979cb8d7c78d16c505adcf.jpeg","path_key":"b7e240d9411d632238ba89c44b4e3736","size":188082,"mime_type":"image\/png","category_id":1,"updated_at":"2022-05-31 17:44:59","created_at":"2022-05-31 17:44:59","id":1,"location":"\/uploads\/9ec2a7c169979cb8d7c78d16c505adcf.jpeg"}
	* @return_param id int(10) 文件ID
    * @return_param origin_filename varchar(100) 原始文件名
    * @return_param filename varchar(100) 文件名
    * @return_param ext varchar(20) 文件后缀
    * @return_param category_id int(10) 分类ID
    * @return_param path varchar(255) 路径
    * @return_param path_key varchar(32) 加密key
    * @return_param size varchar(255) 单位
    * @return_param mime_type varchar(100) 类型
    * @return_param created_at timestamp 创建时间
    * @return_param updated_at timestamp 更新时间
    * @remark 错误信息：文件已存在、文件上传失败
	* @number 99
	*/
    public function storeSystemMedia(
        SystemMediaRequest $request, 
        SystemMediaCategory $systemMediaCategory
    ){
        if (Config::getConfigValue('filesystem_disk')=='qiniu') {
            $auth = new Auth(env('QINIU_ACCESS_KEY'), env('QINIU_SECRET_KEY'));
            $bucketManager = new BucketManager($auth);
            $buckets = current($bucketManager->buckets());
            if (!$buckets) {
                return $this->error("QINIU_ACCESS_KEY或QINIU_SECRET_KEY错误！");
            }
            if (!in_array(env('QINIU_BUCKET'), $buckets)) {
                return $this->error(env('QINIU_BUCKET')."仓库不存在！");
            }
        }
        $files = $this->saveFiles($request);
        if (isset($files['file']['existed'])) {
            if ($files['file']['existed']) {
                return $this->error('文件 '.$files['file']['origin_filename'].' 已存在');
            } else {
                $media = $systemMediaCategory->media()->create($files['file']);
                return $this->created(SystemMediaResource::make($media));
            }
        } else {
            return $this->error('文件 '.$files['file']['origin_filename'].' 上传失败');
        }
    }
}
